﻿using System.Xml;

namespace NJabber.Stream.Elements
{
    public class MessageStanza : Stanza
    {
        public MessageStanza() : base("message")
        { }

        public string Subject { get; set; }

        public string Body { get; set; }

        public object ParentThreadId { get; set; }

        public object ThreadId { get; set; }

        protected override void WritePayload(XmlWriter writer)
        {
            base.WritePayload(writer);
            WriteSubject(writer);
            WriteBody(writer);
            WriteThreadId(writer);
        }

        private void WriteSubject(XmlWriter writer)
        {
            if (!string.IsNullOrEmpty(Subject)) writer.WriteElementString("subject", Subject);
        }

        private void WriteBody(XmlWriter writer)
        {
            if (!string.IsNullOrEmpty(Body)) writer.WriteElementString("body", Body);
        }

        private void WriteThreadId(XmlWriter writer)
        {
            string threadIdValue = ThreadId == null ? "" : ThreadId.ToString();
            string parentThreadIdValue = ParentThreadId == null ? "" : ParentThreadId.ToString();
            if (string.IsNullOrEmpty(threadIdValue)) return;
            writer.WriteStartElement("thread");
            if (!string.IsNullOrEmpty(parentThreadIdValue)) writer.WriteAttributeString("parent", parentThreadIdValue);
            writer.WriteString(threadIdValue);
            writer.WriteEndElement();
        }

        public override bool Equals(object obj)
        {
            MessageStanza message = obj as MessageStanza;
            if (obj == null) return false;
            return Equals(message);
        }

        public bool Equals(MessageStanza message)
        {
            return base.Equals(message) 
                && AreValuesEquals(Subject, message.Subject)
                && AreValuesEquals(Body, message.Body)
                && AreValuesEquals(ThreadId, message.ThreadId)
                && AreValuesEquals(ParentThreadId, message.ParentThreadId);
        }
    }
}
